package com.wm.machine.baselibrary.utils;

import android.content.Context;

/**
 * Author： cxp
 * Description: 屏幕密度和像素转换的 工具类
 */
public final class DensityUtils {
    private static final float FIVE = 0.5f;
  private DensityUtils() {
    throw new UnsupportedOperationException("DensityUtils cannot be instantiated");
  }

  /**
   * dp 转 px
   *
   * @param context  app的context
   * @param dpValue dp数值
   * @return px数值
   */
  public static int dp2px(Context context, float dpValue) {
    float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + FIVE);
    // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
    // dpVal, context.getResources().getDisplayMetrics());
  }

  /**
   * sp 转 px
   *
   * @param context app的context
   * @param spValue sp数值
   * @return px数值
   */
  public static int sp2px(Context context, float spValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + FIVE);
    // return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
    // spValue, context.getResources().getDisplayMetrics());
  }


  /**
   * px 转 dp
   *
   * @param context app的context
   * @param pxValue px数值
   * @return dp数值
   */
  public static int px2dp(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + FIVE);
  }

  /**
   * px 转 sp
   *
   * @param context app的context
   * @param pxValue px数值
   * @return sp数值
   */
  public static int px2sp(Context context, float pxValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (pxValue / scale + FIVE);
    // return (int)(pxValue / context.getResources().getDisplayMetrics().scaledDensity);
  }
}
